import express from 'express';
import {
  createPost,
  getPosts,
  getUserPosts,
  getPostById,
  updatePost,
  updatePostStatus,
  deletePost,
  reviewPost,
  getPendingPosts,
  getAllPostsForAdmin,
  getPostStats,
  deletePostAdmin
} from '../controllers/postController.js';
import { authenticateToken, authenticateAdmin } from '../utils/jwt.js';
import {
  validateRequest,
  postSchema,
  postStatusUpdateSchema,
  adminReviewSchema,
  adminPostUpdateSchema,
  paginationSchema,
  postListQuerySchema
} from '../utils/validation.js';

const router = express.Router();

// 验证中间件
const postValidation = validateRequest(postSchema, 'body');
const adminPostUpdateValidation = validateRequest(adminPostUpdateSchema, 'body');
const statusUpdateValidation = validateRequest(postStatusUpdateSchema, 'body');
const adminReviewValidation = validateRequest(adminReviewSchema, 'body');
const paginationValidation = validateRequest(paginationSchema, 'query');
const postListQueryValidation = validateRequest(postListQuerySchema, 'query');

// 条件验证中间件 - 根据用户类型选择验证规则
const conditionalPostValidation = (req, res, next) => {
  // 先进行身份验证
  authenticateToken(req, res, (err) => {
    if (err) {
      return res.status(401).json({ message: '未授权访问' });
    }

    // 根据用户是否是管理员选择验证规则
    if (req.user && req.user.isAdmin) {
      // 管理员使用宽松的验证规则
      adminPostUpdateValidation(req, res, next);
    } else {
      // 普通用户使用严格的验证规则
      postValidation(req, res, next);
    }
  });
};

// 可选的认证中间件（用于某些需要区分用户身份但不强制登录的路由）
const optionalAuth = (req, res, next) => {
  const token = req.headers.authorization?.replace('Bearer ', '');
  if (token) {
    // 如果有token，尝试验证
    authenticateToken(req, res, (err) => {
      if (err) {
        // 如果token无效，清除用户信息但继续执行
        req.user = null;
      }
      next();
    });
  } else {
    // 如果没有token，直接继续
    req.user = null;
    next();
  }
};

/**
 * @route POST /api/posts
 * @desc 创建寻宠帖子
 * @access Private (User)
 */
router.post('/', authenticateToken, postValidation, createPost);

/**
 * @route GET /api/posts
 * @desc 获取帖子列表（公开，已审核通过的）
 * @access Public
 */
router.get('/', postListQueryValidation, getPosts);

/**
 * @route GET /api/posts/my
 * @desc 获取当前用户的帖子列表
 * @access Private (User)
 */
router.get('/my', authenticateToken, paginationValidation, getUserPosts);

/**
 * @route GET /api/posts/pending
 * @desc 获取待审核帖子列表
 * @access Private (Admin)
 */
router.get('/pending', authenticateAdmin, paginationValidation, getPendingPosts);

/**
 * @route GET /api/posts/admin/all
 * @desc 获取所有帖子列表（管理员用，不限制帖子状态）
 * @access Private (Admin)
 */
router.get('/admin/all', authenticateAdmin, paginationValidation, getAllPostsForAdmin);

/**
 * @route GET /api/posts/stats
 * @desc 获取帖子统计信息
 * @access Private (Admin)
 */
router.get('/stats', authenticateAdmin, getPostStats);

/**
 * @route GET /api/posts/:id
 * @desc 根据ID获取帖子详情
 * @access Public (但未审核的帖子只有作者和管理员可见)
 */
router.get('/:id', optionalAuth, getPostById);

/**
 * @route PUT /api/posts/:id
 * @desc 更新帖子信息
 * @access Private (User - 帖子作者或管理员)
 */
router.put('/:id', conditionalPostValidation, updatePost);

/**
 * @route PATCH /api/posts/:id/status
 * @desc 更新帖子状态（找到/关闭）
 * @access Private (User - 仅帖子作者)
 */
router.patch('/:id/status', authenticateToken, statusUpdateValidation, updatePostStatus);

/**
 * @route DELETE /api/posts/:id
 * @desc 删除帖子
 * @access Private (User - 仅帖子作者)
 */
router.delete('/:id', authenticateToken, deletePost);

/**
 * @route PATCH /api/posts/:id/review
 * @desc 管理员审核帖子
 * @access Private (Admin)
 */
router.patch('/:id/review', authenticateAdmin, adminReviewValidation, reviewPost);

/**
 * @route DELETE /api/posts/:id/admin
 * @desc 管理员删除帖子
 * @access Private (Admin)
 */
router.delete('/:id/admin', authenticateAdmin, deletePostAdmin);

export default router;
